<template>
  <div id="nav" ref="nav" :class="isFixed == true ? 'uzy-nav-wra' : ''">
    <div class="main">
      <div class="logo">
        <img
          :src="
            get(store.getters, 'indexInfo.logo', '../../assets/images/logo.png')
          "
          alt=""
          class="img"
        />
      </div>

      <div style="position: relative">
        <div
          class="region"
          @click.stop="handleCutProvince"
          @mouseover="ishover"
          @mouseout="handleMouseOutProvinceBox($event)"
        >
          {{ isLoginProvince || province.provinceName }}
          <el-icon style="margin-left: 5px" v-if="provinceList.length > 1">
            <ArrowDown />
          </el-icon>
        </div>
        <div
          v-if="!isToken"
          class="provinceList"
          v-show="provinceBox"
          @mouseover="cancelHideProvinceBox"
          @mouseout="hideProvinceBoxLater"
        >
          <div
            @click="handleCheckProvince(prov)"
            class="list-item f14"
            v-for="prov in provinceList"
            :key="prov.id"
          >
            {{ prov.letter }}&nbsp;{{ prov.provinceName }}
          </div>
        </div>
      </div>

      <div class="navList">
        <div
          class="item"
          @click="handleGoNav(item)"
          @mouseover="handleMouseOver(item, index)"
          @mouseout="handleMouseOut(item, index)"
          style="position: relative"
          v-for="(item, index) in navList"
          :key="item.id"
        >
          <div style="display: flex; align-items: center">
            {{ item.title
            }}<el-icon
              v-if="item.children"
              class="icon"
              style="margin-left: 5px"
            >
              <ArrowDown />
            </el-icon>
          </div>
          <div
            :class="[
              `children-box${index}`,
              isActiveBox === index ? 'actveBox' : '',
            ]"
            class="children-box"
          >
            <div
              @click.stop="handleGoUrl(chiln)"
              class="children-item"
              v-for="chiln in item.children"
              :key="chiln.id"
            >
              {{ chiln.title }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { classTypeListApi } from '@/api/zy/index';
import { getProvince } from '../../api/provinces/province';
import { onMounted, ref, onUnmounted } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import bus from '@/utils/bus';
import { get } from 'lodash';
const isToken = ref('');
const store = useStore();
const router = useRouter();
const province = ref({});
const isLoginProvince = ref('');
const provinceBox = ref(false);
const provinceList = ref([]);
const classParams = ref({
  page: 1,
  pageSize: 100,
});
const navList = ref([
  { id: 1, title: '首页', url: '/home' },
  {
    id: 2,
    title: '智能选科',
    children: [
      { id: 2 - 1, title: '完整智能模式', url: '/optional' },
      { id: 2 - 2, title: '自主选科分析', url: '/optional' },
      { id: 2 - 3, title: '选考科目查询', url: '/optional' },
    ],
  },
  { id: 3, title: '高考资讯', url: '/news' },
  {
    id: 4,
    title: '数据查询',
    children: [
      { id: 4 - 1, title: '找大学', url: '/college/searchCollege' },
      { id: 4 - 2, title: '查专业', url: '/majorLibrary' },
      { id: 4 - 3, title: '分数线', url: '/scoreLine' },
      { id: 4 - 4, title: '位次查询', url: '/positionalQuery' },
      { id: 4 - 5, title: '提前批', url: '/tiQianPi' },
      { id: 4 - 6, title: '看职业', url: '/jorLibrary' },
      { id: 4 - 7, title: '批次线', url: '/picixian' },
    ],
  },
  {
    id: 5,
    title: '填志愿',
    children: [
      { id: 5 - 1, title: '专家一对一填报', url: '/expert-one-on-one' },
      { id: 5 - 2, title: '一键填报', url: '/batchInfo' },
      { id: 5 - 3, title: '院校优先填报', url: '/batchInfo' },
      { id: 5 - 4, title: '专业优先填报', url: '/batchInfo' },
      { id: 5 - 5, title: '职业优先填报', url: '/batchInfo' },
    ],
  },
  // 志愿讲堂
  {
    id: 7,
    title: '升学课堂',
    children: [{ id: 7 - 5, title: '视频课', url: '/ziYclassrooms' }],
  },
  { id: 6, title: '学生测评', url: '/appraisal' },
  { id: 6, title: '服务', url: '/shopserve' },
  { id: 6, title: '咨询师', url: '/experts' },
]);
let hideProvinceBoxTimer;
const isActiveBox = ref('');

// 课程类别
const classTypeList = async () => {
  const { data } = await classTypeListApi(classParams.value);

  const filterList = navList.value.find((item) => item.id == 7);
  // 将  data.data.data 添加到 children 中
  data.data.data.forEach((item) => {
    filterList.children.push({
      id: item.id, // 使用 pushData 的 id
      title: item.name, // 使用 pushData 的 name 作为标题
      url: `/ziYclassrooms?id=${item.id}`, // 假设需要一个动态 URL
    });
  });
};

const handleCheckProvince = (prov) => {
  store.dispatch('province/changeProvince', prov);
  province.value = store.getters.province.provinceData;
  hideProvinceBoxLater();
};

const handleMouseOver = (item, index) => {
  isActiveBox.value = item.children ? index : -1;
  if (item.children) {
    const icon = document
      .getElementsByClassName('item')
      [index].querySelector('.icon');
    if (icon) {
      icon.style.transform = 'rotate(180deg)';
    }
  }
};
const handleMouseOut = (item, index) => {
  isActiveBox.value = -1;
  if (item.children) {
    const icon = document
      .getElementsByClassName('item')
      [index].querySelector('.icon');
    if (icon) {
      icon.style.transform = 'rotate(0deg)';
    }
  }
};
const handleMouseOutProvinceBox = (event) => {
  if (!isToken.value) {
    let region = document.querySelector('.region');
    let provinceListDiv = document.querySelector('.provinceList');
    let isHovered =
      region.contains(event.relatedTarget) ||
      provinceListDiv.contains(event.relatedTarget);
    if (!isHovered) {
      hideProvinceBoxLater();
    }
  }
};

const hideProvinceBoxLater = () => {
  hideProvinceBoxTimer = setTimeout(() => {
    provinceBox.value = false;
  }, 200);
};

const cancelHideProvinceBox = () => {
  if (provinceList.value.length > 1) {
    clearTimeout(hideProvinceBoxTimer);
  }
};
const ishover = () => {
  if (provinceList.value.length > 1) {
    provinceBox.value = true;
  }
};
// 切换省份
const handleCutProvince = () => {};
const fetchProvince = () => {
  getProvince().then((res) => {
    if (res.data.code == 20000) {
      isToken.value = store.getters.user.token;
      store.dispatch('province/changeAllProvince', res.data.data);
      localStorage.setItem('provinceList', JSON.stringify(res.data.data));
      province.value = res.data.data[0];
      store.dispatch('province/changeProvince', res.data.data[0]);
      store.dispatch('user/changeProvinceData', res.data.data[0]);
      isLoginProvince.value = store.getters.user.userInfo.province;
      store.getters.user.userInfo.pid
        ? bus.emit('handleIsGkb', store.getters.user.userInfo)
        : bus.emit('handleIsGkb', res.data.data[1]);
      provinceList.value = res.data.data;
    }
  });
};
const handleGoNav = (item) => {
  router.push({
    path: item.url,
  });
};
const handleGoUrl = (item) => {
  if (item.url.includes('/ziYclassrooms')) {
    if (item.title == '视频课') {
      router.push({ path: item.url, query: { id: 0 } });
    } else {
      router.push({ path: item.url, query: { id: item.id } });
    }
    return;
  }
  router.push({ path: item.url });
};

const isFixed = ref(false); // 是否固定
const nav = ref(null); // 导航栏元素
let navbarOffsetTop = 0; // 导航栏初始的距离顶部距离

// 监听滚动事件
const handleScroll = () => {
  const scrollTop = window.scrollY || document.documentElement.scrollTop;
  isFixed.value = scrollTop >= navbarOffsetTop; // 滚动超过初始位置时固定导航栏
};

onMounted(() => {
  classTypeList();
  // 获取导航栏初始的距离顶部距离
  if (nav.value) navbarOffsetTop = nav.value.offsetTop;

  fetchProvince();
  // 添加滚动监听
  window.addEventListener('scroll', handleScroll);
});
onUnmounted(() => {
  // 移除滚动监听
  window.removeEventListener('scroll', handleScroll);
});
</script>

<style lang="scss" scoped>
.logo {
  height: 45px;
  max-width: 270px;
  .img {
    height: 100%;
  }
}
.provinceList {
  cursor: pointer;
  background: #fff;
  display: flex;
  // display: none;
  width: 385px;
  position: absolute;
  top: 30px;
  left: 35px;
  z-index: 999;
  flex-wrap: wrap;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 6px;

  .list-item {
    width: 90px;
    text-align: center;
    padding: 0px 10px;
    height: 35px;
    line-height: 35px;
    margin: 10px 0;

    &:hover {
      background-color: var(--background-color);
      color: #fff;
    }
  }
}

.icon {
  transition: transform 0.3s ease-in-out;
  /* 添加过渡效果 */
}

// #nav.uzy-nav-wra {
//   position: fixed;
//   top: 0;
//   left: 0;
//   width: 100%;
//   z-index: 10000000;
//   background-color: #fff;
// }
#nav {
  width: 100%;
  border-bottom: 1px solid rgb(226, 226, 226);

  .main {
    display: flex;
    align-items: center;

    .region {
      width: 140px;
      display: flex;
      align-items: center;
      cursor: pointer;
      margin-left: 36px;

      &:hover {
        color: var(--active-text);
      }
    }
  }

  .navList {
    display: flex;
    cursor: pointer;

    .item {
      margin: 0 10px;

      &:hover {
        color: var(--active-text);
      }
    }
  }

  .children-box {
    z-index: 999;
    transform-origin: top;
    transform: scaleY(0);
    opacity: 0;
    transition: all 0.2s ease-in-out;
    position: absolute;
    top: 50px;
    left: 0;
    background: #333;
    border-radius: 10px;

    .children-item {
      color: #fff;
      padding: 10px 10px;
    }
  }

  .children-box1 {
    width: 120px;
  }

  .children-box4 {
    width: 140px;
  }
  .children-box5 {
    width: 120px;
  }

  .children-box6 {
    width: 230px;
  }
}

.active {
  color: red;
}

.actveBox {
  transform: scaleY(1) !important;
  opacity: 1 !important;
}
</style>
